package com.ruoyi.system.V2.phone.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.gameInfo.mapper.GameInfoMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.model.domain.GameInfo;
import com.ruoyi.system.model.domain.GoodsInfo;
import com.ruoyi.system.model.domain.TelManage;
import com.ruoyi.system.V2.phone.mapper.TelManageMapper;
import com.ruoyi.system.V2.phone.service.ITelManageService;
import com.ruoyi.system.telManage.service.ITelManageHistoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 手机管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-05
 */
@Service
public class TelManageServiceImpl implements ITelManageService {

    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @Resource
    private TelManageMapper telManageMapper;
    @Autowired
    private GameInfoMapper gameInfoMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ITelManageHistoryService telManageHistoryService;

    /**
     * 查询手机管理
     *
     * @param id 手机管理主键
     * @return 手机管理
     */
    @Override
    public TelManage selectTelManageById(Long id) {
        return telManageMapper.selectTelManageById(id);
    }

    /**
     * 查询手机列表
     *
     * @param telManage 手机管理
     * @return
     */
    public List<TelManage> selectTelList(TelManage telManage) {
        return telManageMapper.selectTelManageList(telManage);
    }

    /**
     * 查询手机管理列表
     *
     * @param telManage 手机管理
     * @return 手机管理
     */
    @Override
    public AjaxResult selectTelManageList1(TelManage telManage, PageDomain pageDomain) {
        long index = System.currentTimeMillis();
        Long userId = SecurityUtils.getUserId();
        if (!Objects.equals(userId, 1L)) {
            SysUser user = new SysUser();
            user.setRoleId(113L);
            user.setUserId(userId);
            List<SysUser> users = userMapper.selectAllocatedList(user);
            if (CollectionUtils.isEmpty(users)) {
                telManage.setCreateId(userId);
            }
        }

        GameInfo gameInfo = new GameInfo();
        List<GameInfo> gameInfos = gameInfoMapper.selectGameInfoList(gameInfo);
        Map<Long, GameInfo> listMap = gameInfos.stream().collect(Collectors.toMap(S -> S.getId(), S -> S));
        if (Objects.nonNull(telManage.getGame())) {
            GameInfo info = listMap.get(telManage.getGame());
            telManage.setGameType(info.getGameType());
        }
        List<TelManage> telManages = telManageMapper.selectTelManageList(telManage);
        if (CollectionUtils.isEmpty(telManages)) {
            return AjaxResult.success();
        }


        GoodsInfo goodsInfo = new GoodsInfo();
        List<Long> list = new ArrayList<>();
        for (TelManage manage : telManages) {
            list.add(manage.getId());
        }
        goodsInfo.setTelIds(list);
        goodsInfo.setSaleState(1);
        List<GoodsInfo> goodsInfoList = goodsInfoMapper.selectGoodsInfoList1(goodsInfo);
        goodsInfo.setSaleState(0);
        List<GoodsInfo> goodsInfoList1 = goodsInfoMapper.selectGoodsInfoList1(goodsInfo);


        if (CollectionUtils.isNotEmpty(goodsInfoList1)) {
            goodsInfoList.addAll(goodsInfoList1);
        }
        if (CollectionUtils.isNotEmpty(goodsInfoList)) {
            Map<Long, List<GoodsInfo>> collect = goodsInfoList.stream().collect(Collectors.groupingBy(s -> s.getTelid()));
            for (TelManage manage : telManages) {
                StringBuffer str = new StringBuffer();
                List<GoodsInfo> goodsInfos = collect.get(manage.getId());
                if (CollectionUtils.isNotEmpty(goodsInfos)) {
                    Set<String> collect1 = goodsInfos.stream().map(a -> a.getGameName()).collect(Collectors.toSet());
                    for (String s : collect1) {
                        str.append(s + ":");
                        for (GoodsInfo info : goodsInfoList) {
                            if (Objects.equals(s, info.getGameName())) {
                                str.append(info.getAccountNumber() + ",");
                            }
                        }
                    }
                }
                manage.setGameStr(str.toString());
            }


            for (TelManage manage : telManages) {
                if (StringUtils.equals(manage.getGameType(), "腾讯")) {
                    buildPhoneGame(collect.get(manage.getId()), manage, listMap);
                }
                if (Objects.nonNull(telManage.getGame())) {
                    GameInfo info = listMap.get(telManage.getGame());
                    String gameType = info.getGameType();
                    if (StringUtils.equals(gameType, "网易")) {
                        if (Objects.equals(manage.getWyStatus(), "4") || Objects.equals(manage.getWyStatus(), "3") || Objects.equals(manage.getWyStatus(), "2")) {
                            manage.setIsTrue(false);
                        }
                    }
                }
            }


            if (Objects.nonNull(telManage.getGame())) {
                GameInfo info = listMap.get(telManage.getGame());
                String gameType = info.getGameType();
                if (StringUtils.equals(gameType, "腾讯")) {
                    telManages = telManages.stream()
                            .sorted(Comparator.comparing(TelManage::getTengxunCount).reversed())
                            .collect(Collectors.toList());
                }
            }
            if (Objects.nonNull(telManage.getGameType())) {
                if (StringUtils.equals(telManage.getGameType(), "腾讯")) {
                    telManages = telManages.stream()
                            .sorted(Comparator.comparing(TelManage::getTengxunCount).reversed())
                            .collect(Collectors.toList());
                }
            }
        }


        Integer pageNum = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
        Integer pageSize = pageDomain.getPageSize() + pageNum;
        int total = telManages.size();
        if (pageNum >= total) {
            pageNum = total;
        }
        if (pageSize >= total) {
            pageSize = total;
        }
        List<TelManage> rows = telManages.subList(pageNum, pageSize);

        AjaxResult result = AjaxResult.success();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @Override
    public List<TelManage> selectTelManageList(TelManage telManage) {
        Long userId = SecurityUtils.getUserId();
        if (!Objects.equals(userId, 1L)) {
            SysUser user = new SysUser();
            user.setRoleId(113L);
            user.setUserId(userId);
            List<SysUser> users = userMapper.selectAllocatedList(user);
            if (CollectionUtils.isEmpty(users)) {
                telManage.setCreateId(userId);
            }
        }


        GameInfo gameInfo = new GameInfo();
        List<GameInfo> gameInfos = gameInfoMapper.selectGameInfoList(gameInfo);
        Map<Long, GameInfo> listMap = gameInfos.stream().collect(Collectors.toMap(S -> S.getId(), S -> S));
        if (Objects.nonNull(telManage.getGame())) {
            GameInfo info = listMap.get(telManage.getGame());
            telManage.setGameType(info.getGameType());
        }
        List<TelManage> telManages = telManageMapper.selectTelManageList(telManage);
        if (CollectionUtils.isEmpty(telManages)) {
            return telManages;
        }


        GoodsInfo goodsInfo = new GoodsInfo();
        List<Long> list = new ArrayList<>();
        for (TelManage manage : telManages) {
            list.add(manage.getId());
        }
        goodsInfo.setTelIds(list);
        goodsInfo.setSaleState(1);
        List<GoodsInfo> goodsInfoList = goodsInfoMapper.selectGoodsInfoList1(goodsInfo);
        goodsInfo.setSaleState(0);
        List<GoodsInfo> goodsInfoList1 = goodsInfoMapper.selectGoodsInfoList1(goodsInfo);


        if (CollectionUtils.isNotEmpty(goodsInfoList1)) {
            goodsInfoList.addAll(goodsInfoList1);
        }
        if (CollectionUtils.isNotEmpty(goodsInfoList)) {
            Map<Long, List<GoodsInfo>> collect = goodsInfoList.stream().collect(Collectors.groupingBy(s -> s.getTelid()));
            for (TelManage manage : telManages) {
                StringBuffer str = new StringBuffer();
                List<GoodsInfo> goodsInfos = collect.get(manage.getId());
                if (CollectionUtils.isNotEmpty(goodsInfos)) {
                    Set<String> collect1 = goodsInfos.stream().map(a -> a.getGameName()).collect(Collectors.toSet());
                    for (String s : collect1) {
                        str.append(s + ":");
                        for (GoodsInfo info : goodsInfoList) {
                            if (Objects.equals(s, info.getGameName())) {
                                str.append(info.getAccountNumber() + ",");
                            }
                        }
                    }
                }
                manage.setGameStr(str.toString());
            }


            for (TelManage manage : telManages) {
                if (StringUtils.equals(manage.getGameType(), "腾讯")) {
                    buildPhoneGame(collect.get(manage.getId()), manage, listMap);
                }
                if (Objects.nonNull(telManage.getGame())) {
                    GameInfo info = listMap.get(telManage.getGame());
                    String gameType = info.getGameType();
                    if (StringUtils.equals(gameType, "网易")) {
                        if (Objects.equals(manage.getWyStatus(), "4") || Objects.equals(manage.getWyStatus(), "3") || Objects.equals(manage.getWyStatus(), "2")) {
                            manage.setIsTrue(false);
                        }
                    }
                }
            }


            if (Objects.nonNull(telManage.getGame())) {
                GameInfo info = listMap.get(telManage.getGame());
                String gameType = info.getGameType();
                if (StringUtils.equals(gameType, "腾讯")) {
                    telManages = telManages.stream()
                            .sorted(Comparator.comparing(TelManage::getTengxunCount).reversed())
                            .collect(Collectors.toList());
                }
            }
            if (Objects.nonNull(telManage.getGameType())) {
                if (StringUtils.equals(telManage.getGameType(), "腾讯")) {
                    telManages = telManages.stream()
                            .sorted(Comparator.comparing(TelManage::getTengxunCount).reversed())
                            .collect(Collectors.toList());
                }
            }
        }
        return telManages;
    }

    public void buildPhoneGame(List<GoodsInfo> goodsInfoList, TelManage manage, Map<Long, GameInfo> listMap) {
        if (CollectionUtils.isNotEmpty(goodsInfoList)) {
            for (GoodsInfo goodsInfo : goodsInfoList) {
                goodsInfo.setCarrierType(listMap.get(goodsInfo.getGameId()).getGameType());
            }
            Map<String, List<GoodsInfo>> goodsMap = goodsInfoList.stream()
                    .filter(s -> Objects.nonNull(s.getCarrierType()))
                    .collect(Collectors.groupingBy(s -> s.getCarrierType()));
            // 腾讯
            if (true) {
                List<GoodsInfo> goodsInfos = goodsMap.get("腾讯");
                if (CollectionUtils.isNotEmpty(goodsInfos)) {
                    Set<String> collect = goodsInfos.stream().map(s -> s.getAccountNumber()).collect(Collectors.toSet());
                    int size = 5 - collect.size();
                    if (size < 1) {
                        manage.setIsTrue(false);
                    }
                    manage.setTengxunCount(size);
                }
            }
            if (true) {
            }
            //网易
            if (true) {
            }
            //其他
            if (true) {

            }
        }
    }

    /**
     * 新增手机管理
     *
     * @param telManage 手机管理
     * @return 结果
     */
    @Override
    public int insertTelManage(TelManage telManage) {
        telManage.setCreateTime(DateUtils.getNowDate());
        telManage.setCreateId(SecurityUtils.getUserId());

        TelManage tel = new TelManage();
        tel.setTel(telManage.getTel());
        tel.setGameType(telManage.getGameType());
        List<TelManage> telManages = telManageMapper.selectTelManageList(tel);
        if (CollectionUtils.isNotEmpty(telManages)) {
            throw new GlobalException("该手机号已存在");
        }
        if (Objects.isNull(telManage.getWyStatus())) {
            telManage.setWyStatus("1");
        }
        int manage = telManageMapper.insertTelManage(telManage);

        return manage;
    }

    /**
     * 修改手机管理
     *
     * @param telManage 手机管理
     * @return 结果
     */
    @Override
    public int updateTelManage(TelManage telManage) {
        telManage.setUpdateTime(DateUtils.getNowDate());
        telManage.setUpdateId(SecurityUtils.getUserId());

        TelManage tel = new TelManage();
        tel.setTel(telManage.getTel());
        tel.setGameType(telManage.getGameType());
        List<TelManage> telManages = telManageMapper.selectTelManageList(tel);
        if (CollectionUtils.isNotEmpty(telManages) && !(Objects.equals(telManages.get(0).getTel(), telManage.getTel()))) {
            throw new GlobalException("该手机号已存在");
        }
        int manage = telManageMapper.updateTelManage(telManage);
        return manage;
    }

    /**
     * 修改手机管理
     *
     * @param telManage 手机管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTelNull(TelManage telManage) {
        if (Objects.isNull(telManage.getId())) {
            throw new GlobalException("商品未绑定手机号ID");
        }
//        TelManage manage = telManageMapper.selectTelManageById(telManage.getId());
        if (
//                Objects.nonNull(manage.getWyGoodsId()) &&
                Objects.equals(telManage.getWyStatus(), "2")) {
            GoodsInfo goodsInfo = new GoodsInfo();
            goodsInfo.setId(telManage.getWyGoodsId());
            goodsInfo.setUseStatus("1");
            goodsInfoMapper.updateGoodsInfo(goodsInfo);
        }
        return telManageMapper.updateTelNull(telManage);
    }

    /**
     * 批量删除手机管理
     *
     * @param ids 需要删除的手机管理主键
     * @return 结果
     */
    @Override
    public int deleteTelManageByIds(Long[] ids) {
        return telManageMapper.deleteTelManageByIds(ids);
    }

    /**
     * 删除手机管理信息
     *
     * @param id 手机管理主键
     * @return 结果
     */
    @Override
    public int deleteTelManageById(Long id) {
        return telManageMapper.deleteTelManageById(id);
    }

    @Override
    public String countGame(Long id) {

        TelManage telManage = telManageMapper.selectTelManageById(id);

        if (Objects.isNull(telManage)) {
            throw new GlobalException("未查到此手机");
        }

        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setTelid(telManage.getId());
        goodsInfo.setSaleState(1);
        List<GoodsInfo> goodsInfoList = goodsInfoMapper.selectGoodsInfoList(goodsInfo);
        Set<String> collect = goodsInfoList.stream().map(a -> a.getGameName()).collect(Collectors.toSet());
        StringBuffer str = new StringBuffer();
        for (String s : collect) {
            str.append(s + ":");
            for (GoodsInfo info : goodsInfoList) {
                if (Objects.equals(s, info.getGameName())) {
                    str.append(info.getAccountNumber() + ",");
                }
            }
        }
        telManage.setGameStr(str.toString());

        return str.toString();
    }

    @Override
    public List<TelManage> allList(TelManage telManage) {
        List<TelManage> telManages = telManageMapper.selectTelManageList(new TelManage());
        return telManages;
    }


}
